package com.example.minzhengtong.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.FragmentActivity
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bumptech.glide.Glide
import com.example.minzhengtong.Const
import com.example.minzhengtong.base.BaseA
import com.example.minzhengtong.databinding.ActivityPersonalDetailBinding
import com.example.minzhengtong.utils.LogUtil
import com.example.minzhengtong.utils.SnapShot
import com.example.minzhengtong.utils.SpUtil
import com.example.minzhengtong.utils.WUtils
import com.gyf.immersionbar.ImmersionBar
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.request.ExplainScope
import com.permissionx.guolindev.request.ForwardScope
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

/**
 * created by WY on 2021/5/31.
 * 公积金个人账户明细
 */
class PersonalDetailA : BaseA() {

    companion object{
        fun enterThis(context: Context){
            val intent = Intent(context, PersonalDetailA::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var binding : ActivityPersonalDetailBinding

    private val initPath = "${Const.baseIp}account.html?token=${SpUtil.getInstance().getString(Const.TOKEN)}"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(0,0)
        binding = ActivityPersonalDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setToolBarVisiabale(false)

        ImmersionBar.with(this).titleBar(binding.titleBar).statusBarDarkFont(true).init()

        binding.year.isChecked = true

//        Glide.with(baseContext).load(imagePath).into(binding.excel)
//        binding.seal.visibility = View.GONE

        binding.search.visibility = View.VISIBLE
        binding.containerResult.visibility = View.GONE
        binding.containerTop1.visibility = View.VISIBLE
        binding.containerTop2.visibility = View.GONE

        binding.search.setOnClickListener {
            binding.search.visibility = View.GONE
            showDialog(false)
                Thread{
                    Thread.sleep(1000)
                    runOnUiThread {
                        hideDialog()
                        binding.containerTop1.visibility = View.GONE
                        binding.containerTop2.visibility = View.VISIBLE
                        binding.containerResult.visibility = View.VISIBLE
                    }
                }.start()
        }

        binding.save.setOnClickListener {
            initPermission()
        }

        initTime()
        initWeb()

    }

    private val dateFormat = SimpleDateFormat("yyyy/MM/dd")

    private fun initWeb(){
        val settings = binding.webview.settings
        settings.apply {
            javaScriptEnabled = true
            builtInZoomControls = true
            domStorageEnabled = true
            displayZoomControls  = false
            cacheMode = WebSettings.LOAD_NO_CACHE
        }
        //系统版本不小于5.0
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            WebView.enableSlowWholeDocumentDraw()
        }
        binding.webview.apply {
            settings.loadWithOverviewMode = true
            webViewClient = object : WebViewClient(){
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
//                view.loadUrl(url)
//                return super.shouldOverrideUrlLoading(view, url)
                    if (Build.VERSION.SDK_INT < 26) {
                        view.loadUrl(url)
                        return true
                    } else {
                        return false
                    }
                }

                override fun onPageFinished(view: WebView, url: String) {
                    super.onPageFinished(view, url)
                }
            }
        }
    }

    private fun initTime(){
        val calendar = Calendar.getInstance()
        calendar.time = Date()
        calendar.add(Calendar.YEAR, -1)

        binding.start.text = dateFormat.format(calendar.time)
        binding.end.text = dateFormat.format(Date())
        binding.account.text = "个人公积金账户：${userBean?.data?.uzh}"

        binding.start2.text = binding.start.text
        binding.end2.text = binding.end.text

        binding.start.setOnClickListener {
            val pickerView = TimePickerBuilder(
                this
            ) { date, v ->
                binding.start.text = getTime(date)

                binding.start2.text = binding.start.text
                binding.end2.text = binding.end.text
            }.build()
            pickerView.show()
        }

        binding.end.setOnClickListener {
            val pickerView = TimePickerBuilder(
                this
            ) { date, v ->
                binding.end.text = getTime(date)

                binding.start2.text = binding.start.text
                binding.end2.text = binding.end.text
            }.build()
            pickerView.show()
        }

        val loadUrl = initPath + "&account=${userBean?.data?.uzh}&beginDate=${binding.start.text}&endDate=${binding.end.text}"
        LogUtil.d("加载的地址$loadUrl")
        binding.webview.loadUrl(loadUrl)

    }

    private fun getTime(date: Date): String? { //可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.time)
        val format = SimpleDateFormat("yyyy/MM/dd")
        return format.format(date)
    }

    private fun initPermission(){
        val permissions: MutableList<String> =
            ArrayList()
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        PermissionX.init(baseContext as FragmentActivity).permissions(permissions)
            .onExplainRequestReason { scope: ExplainScope, deniedList: List<String?>? ->
                //向用户解释请求权限的意图
                scope.showRequestReasonDialog(
                    deniedList,
                    "需要读取存储权限才可以存储图片",
                    "确定",
                    "取消"
                )
            }
            .onForwardToSettings { scope: ForwardScope, deniedList: List<String?>? ->
                //用户永久拒绝权限后的跳转设置页面开启
                scope.showForwardToSettingsDialog(
                    deniedList,
                    "请到设置中开启读写存储权限",
                    "确定",
                    "取消"
                )
            }
            .request { allGranted: Boolean, grantedList: List<String?>?, deniedList: List<String?>? ->
                if (allGranted) {
                    //获取到相册和权限
                    LogUtil.d("申请权限已获取")
//                    val saveBitmap = SnapShot(binding.webview,1f).apply()
                    val saveBitmap = captureWebView(binding.webview)
                    WUtils.saveImageToGallery(baseContext,saveBitmap)
                } else {
                    //用户拒绝了权限
                    LogUtil.d("申请权限已拒绝")
                }
            }
    }

    private fun  captureWebView(webView : WebView) : Bitmap {
        val snapShot : Picture = webView.capturePicture()
        val bitmap : Bitmap = Bitmap.createBitmap(snapShot.getWidth(), snapShot.getHeight(), Bitmap.Config.ARGB_8888)
        val canvas : Canvas = Canvas(bitmap)
        snapShot.draw(canvas)
        return bitmap
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0,0)
    }

}